/*************************************************************************
	> File Name: io_select.c
	> Author: xuyl
	> Mail: xuyongli2013@hotmail.com 
	> Created Time: 2020年09月09日 星期三 10时57分19秒
 ************************************************************************/
/*
 *此程序用来学习select函数，主要功能是：读取键盘输入值 ，并打印。
 *测试：按下按键，并回车，打印出相对应的值。
 * */
#include<stdio.h>
#include<sys/types.h>
#include<sys/time.h>
#include<fcntl.h>
#include<sys/ioctl.h>
#include<unistd.h>
#include<stdlib.h>


int main()
{
	char buffer[128] = {0};
	int result,nread;
	int keyboard;
	fd_set inputs,testfds;
	struct timeval timeout;

	FD_ZERO(&inputs);
	FD_SET(0,&inputs);
	
	while(1)
	{
		testfds = inputs;
		timeout.tv_sec = 2;
		timeout.tv_usec = 500000;
		result = select(FD_SETSIZE,&testfds,NULL,NULL,&timeout);
		switch(result)
		{
			case 0:
				printf("timeout\n");
				break;
			case -1:
				perror("select");
				exit(1);
			default:
				if(FD_ISSET(0,&testfds))
				{
					ioctl(0,FIONREAD,&nread);//读取串行端口输入缓冲区中的字节数--nread
					if(nread == 0)
					{
						printf("keyboard done\n");
						exit(1);
					}
					nread = read(0,buffer,nread);
					buffer[nread] = 0;

					printf("read %d from keyboard:%s",nread,buffer);
				}
				break;
		}
	}
	return 0;

}

